package pers.cz.utils;

import pers.cz.date.DateUtils;
import org.luaj.vm2.*;

import java.util.*;

/**
 * @program: PostGirl-panent
 * @description: LuaScriptUtils
 * @author: Cheng Zhi
 * @create: 2022-04-21 23:01
 **/
public class LuaScriptUtils {

    public static LuaValue toLua(Object value) {
        if (value == null) {
            return LuaValue.NIL;
        } else if (value instanceof Number) {
            return LuaNumber.valueOf(((Number)value).doubleValue());
        } else if (value instanceof CharSequence) {
            return LuaString.valueOf(value.toString());
        } else if (value instanceof Boolean) {
            return LuaValue.valueOf((Boolean)value);
        } else if (value instanceof Date) {
            return LuaString.valueOf(DateUtils.format((Date)value, "yyyy-MM-dd HH:mm:ss"));
        } else if (value instanceof Byte) {
            return LuaNumber.valueOf(((Byte)value).intValue());
        } else if (value instanceof Map) {
            return mapToLuaTable((Map)value);
        } else if (!value.getClass().isArray() && !(value instanceof Collection)) {
            if (value instanceof LuaValue) {
                return (LuaValue)value;
            } else {
                String name = value.getClass().getName();

                return new LuaUserdata(value);
            }
        } else if (value instanceof Integer) {
            return LuaNumber.valueOf(((Number)value).doubleValue());
        } else {
            return collectionToLua(value);
        }
    }

    public static LuaTable mapToLuaTable(Map<?, ?> map) {
        LuaTable result = new LuaTable();
        Iterator i$ = map.entrySet().iterator();

        while(i$.hasNext()) {
            Map.Entry<?, ?> entry = (Map.Entry)i$.next();
            result.set(toLua(entry.getKey()), toLua(entry.getValue()));
        }

        return result;
    }

    /**
     * 处理数组转luaValue
     * @param rhs
     * @return
     */
    public static LuaValue collectionToLua(Object rhs) {
        LuaTable result = new LuaTable();

        // 判断传入的是否为数组
        List<Object> itable = new ArrayList<>();
        if (rhs.getClass().isArray()) {
            // 将数组转换为List
            for (Object object : (Object[]) rhs) {
                itable.add(object);
            }
        } else {
            throw new IllegalArgumentException("The input value " + rhs + " is not a Array");
        }
        //Iterator<Object> itable = list.iterator();

        //Iterable<?> itable = (Iterable<?>) list.iterator();
        if (itable == null) {
            throw new IllegalArgumentException("The input value " + rhs + " is not a collection");
        } else {
            int n = 1;

            for(Iterator i$ = itable.iterator(); i$.hasNext(); ++n) {
                Object obj = i$.next();
                LuaValue value = toLua(obj);
                result.set(n, value);
            }

            return result;
        }
    }
}
